<template>
  <el-card>
    <h2 class="mb-4">{{ isEditMode ? '编辑课题' : '发布课题' }}</h2>
    <el-form
      ref="topicForm"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="课题名称" prop="title">
        <el-input v-model="form.title" placeholder="请输入课题名称"></el-input>
      </el-form-item>
      <el-form-item label="研究方向" prop="category">
        <el-select v-model="form.category" placeholder="选择研究方向">
          <el-option label="人工智能" value="人工智能"></el-option>
          <el-option label="新材料" value="新材料"></el-option>
          <el-option label="网络安全" value="网络安全"></el-option>
          <el-option label="生物医药" value="生物医药"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="需求描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="5"
          placeholder="请详细描述课题需求、预期成果等"
        ></el-input>
      </el-form-item>
      <el-form-item label="具体要求" prop="requirements">
        <el-input
          v-model="form.requirements"
          type="textarea"
          :rows="3"
          placeholder="请输入对申请者的具体要求"
        ></el-input>
      </el-form-item>
      <el-form-item label="预算(元)" prop="budget">
        <el-input-number
          v-model="form.budget"
          :min="0"
          :step="1000"
          placeholder="请输入预算金额"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-select
          v-model="form.tags"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="请选择或输入标签"
        >
          <el-option
            v-for="tag in commonTags"
            :key="tag"
            :label="tag"
            :value="tag"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="截止日期" prop="deadline">
        <el-date-picker
          v-model="form.deadline"
          type="date"
          placeholder="选择截止日期"
          value-format="YYYY-MM-DD"
          :disabled-date="disabledDate"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="是否公开" prop="is_public">
        <el-radio-group v-model="form.is_public">
          <el-radio label="true">公开</el-radio>
          <el-radio label="false">不公开</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">{{ isEditMode ? '保存修改' : '发布课题' }}</el-button>
        <el-button @click="$router.go(-1)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import {
  createProject,
  getProjectDetail,
  updateProject
} from '@/api/enterpriseTypes';

const route = useRoute();
const router = useRouter();
const topicForm = ref<any>(null);
const isEditMode = !!route.params.id;

// 常用标签列表
const commonTags = ref([
  '机器学习',
  '深度学习',
  '大数据',
  '云计算',
  '物联网',
  '区块链',
  '前端开发',
  '后端开发'
]);

const form = reactive({
  title: '',
  category: '',
  description: '',
  requirements: '',
  budget: 0,
  tags: [] as string[],
  deadline: '',
  is_public: 'true',
  contact_info: ''
});

const rules = {
  title: [{ required: true, message: '请输入课题名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择研究方向', trigger: 'change' }],
  description: [{ required: true, message: '请输入需求描述', trigger: 'blur' }],
  requirements: [{ required: true, message: '请输入具体要求', trigger: 'blur' }],
  budget: [
    { required: true, message: '请输入预算金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '预算必须大于0', trigger: 'blur' }
  ],
  deadline: [{ required: true, message: '请选择截止日期', trigger: 'change' }],
  tags: [{ required: true, message: '请选择至少一个标签', trigger: 'change' }],
  is_public: [{ required: true, message: '请选择是否公开', trigger: 'change' }]
};

// 禁止选择过去的日期
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7;
};

// 编辑模式：获取课题详情
onMounted(async () => {
  if (isEditMode) {
    try {
      const res = await getProjectDetail(Number(route.params.id));
      if (res) {
        form.title = res.title || '';
        form.category = res.category || '';
        form.description = res.description || '';
        form.requirements = res.requirements || '';
        form.budget = res.budget || 0;
        form.tags = res.tags || [];
        form.deadline = res.deadline || '';
        form.is_public = res.is_public ? 'true' : 'false';
        form.contact_info = res.contact_info || '';
      }
    } catch (error) {
      ElMessage.error('获取课题详情失败');
    }
  }
});

const handleSubmit = async () => {
  await topicForm.value.validate();
  try {
    const payload = {
      ...form,
      deadline: new Date(form.deadline).toISOString(), // 转换为 ISO 格式
      is_public: form.is_public === 'true'  // 转换为布尔值
    };

    if (isEditMode) {
      await updateProject(Number(route.params.id), payload);
      ElMessage.success('课题修改成功');
    } else {
      await createProject(payload);
      ElMessage.success('课题发布成功');
    }
    router.push('/enterprise/projects');
  } catch (error) {
    ElMessage.error(isEditMode ? '修改失败' : '发布失败');
  }
};
</script>
